package cz.data.domain.metadata.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import cz.data.common.mybatis.BaseServiceImpl;
import cz.data.common.exception.DataException;
import cz.data.common.redis.config.CacheNames;
import cz.data.common.utils.SecurityUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import cz.data.common.utils.SpringContextHolder;
import cz.data.domain.metadata.dao.MetadataTableDao;
import cz.data.domain.metadata.listener.event.MetadataTableDeleteEvent;
import cz.data.domain.metadata.mapstruct.MetadataColumnMapper;
import cz.data.domain.metadata.mapstruct.MetadataTableMapper;
import cz.data.domain.metadata.model.dto.MetadataColumnDto;
import cz.data.domain.metadata.model.dto.MetadataTableDto;
import cz.data.domain.metadata.model.entity.MetadataColumnEntity;
import cz.data.domain.metadata.model.entity.MetadataTableEntity;
import cz.data.domain.metadata.model.enums.DataLevel;
import cz.data.domain.metadata.model.query.MetadataTableQuery;
import cz.data.domain.metadata.service.MetadataAuthorizeService;
import cz.data.domain.metadata.service.MetadataColumnService;
import cz.data.domain.metadata.service.MetadataTableService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class MetadataTableServiceImpl extends BaseServiceImpl<MetadataTableDao, MetadataTableEntity> implements MetadataTableService {

    @Autowired
    private MetadataTableDao metadataTableDao;

    @Autowired
    private MetadataTableMapper metadataTableMapper;
    @Autowired
    private MetadataColumnMapper metadataColumnMapper;
    @Lazy
    @Autowired
    MetadataColumnService metadataColumnService;
    @Autowired
    MetadataAuthorizeService metadataAuthorizeService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MetadataTableEntity saveMetadataTable(MetadataTableDto metadataTableDto) {
        MetadataTableEntity metadataTableEntity = metadataTableMapper.toEntity(metadataTableDto);
        metadataTableDao.insert(metadataTableEntity);
        List<MetadataColumnDto> tableColumns = metadataTableDto.getTableColumns();
        if (CollectionUtils.isNotEmpty(tableColumns)) {
            int index = 1;
            for (MetadataColumnDto tableColumn : tableColumns) {
                MetadataColumnEntity column = metadataColumnMapper.toEntity(tableColumn);
                column.setId(null);
                column.setSourceId(metadataTableEntity.getSourceId());
                column.setTableId(metadataTableEntity.getId());
                if (StringUtils.isBlank(column.getColumnPosition())) {
                    column.setColumnPosition(String.valueOf(index));
                }
                metadataColumnService.save(column);
                index++;
            }
        }
        return metadataTableEntity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = CacheNames.CACHE_1HOUSE, key = "'metadata:table:' + #root.args[0].id")
    public MetadataTableEntity updateMetadataTable(MetadataTableDto metadataTableDto) {
        MetadataTableEntity metadataTableEntity = metadataTableMapper.toEntity(metadataTableDto);
        metadataTableDao.updateById(metadataTableEntity);
        return metadataTableEntity;
    }

    @Override
    @Cacheable(cacheNames = CacheNames.CACHE_1HOUSE, key = "'metadata:table:' + #id", unless = "#result == null")
    public MetadataTableEntity getMetadataTableById(String id) {
        return super.getById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteMetadataTableById(String id) {
        metadataTableDao.deleteById(id);
        SpringContextHolder.publishEvent(new MetadataTableDeleteEvent(id));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteMetadataTableBatch(List<String> ids) {
        metadataTableDao.deleteBatchIds(ids);
        ids.stream().map(MetadataTableDeleteEvent::new).forEach(SpringContextHolder::publishEvent);
    }

    @Override
    public void deleteMetadataTableBySourceId(String sourceId) {
        List<MetadataTableEntity> list = getMetadataTableBySourceId(sourceId);
        List<String> ids = list.stream().map(MetadataTableEntity::getId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(ids)) {
            this.deleteMetadataTableBatch(ids);
        }
    }

    @Override
    public List<MetadataTableEntity> getDataMetadataTableList(MetadataTableQuery metadataTableQuery) {
        boolean admin = SecurityUtil.isAdmin();
        if (StringUtils.isBlank(metadataTableQuery.getSourceId())) {
            throw new DataException("数据源不能为空");
        }
        List<MetadataTableEntity> tableList = this.getMetadataTableBySourceId(metadataTableQuery.getSourceId());
        Stream<MetadataTableEntity> stream = Optional.ofNullable(tableList).orElseGet(ArrayList::new).stream();
        if (!admin) {
            List<String> roleIds = SecurityUtil.getUserRoleIds();
            Set<String> set = metadataAuthorizeService.authorities(roleIds, DataLevel.TABLE.getKey()::equals);
            stream = stream.filter(s -> set.contains(s.getId()));
        }
        return stream.collect(Collectors.toList());
    }

    @Override
    public <E extends IPage<MetadataTableEntity>> E pageWithAuth(E page, Wrapper<MetadataTableEntity> queryWrapper) {
        boolean admin = SecurityUtil.isAdmin();
        List<String> roles = new ArrayList<>();
        if (!admin) {
            roles = SecurityUtil.getUserRoleIds();
        }
        return metadataTableDao.selectPageWithAuth(page, queryWrapper, roles);
    }

    @Override
    public List<MetadataTableEntity> getMetadataTableBySourceId(String sourceId) {
        QueryWrapper<MetadataTableEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MetadataTableEntity::getSourceId, sourceId);
        return list(queryWrapper);
    }

    @Override
    public MetadataTableEntity getMetadataTableBySourceIdAndTableName(String source, String table) {
        QueryWrapper<MetadataTableEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(MetadataTableEntity::getSourceId, source)
                .eq(MetadataTableEntity::getTableName, table);
        return getOne(wrapper);
    }
}
